package com.wxblockchain.prometheum.managers;

import android.text.TextUtils;

import com.wxblockchain.core.utils.LogUtil;

import java.lang.ref.WeakReference;
import java.util.concurrent.ConcurrentHashMap;

import io.flutter.embedding.android.FlutterFragment;

public class FlutterFragmentManager {
    private final String TAG = this.getClass().getSimpleName();

    private static final ConcurrentHashMap<String, WeakReference<FlutterFragment>> fragmentCacheHashMap;

    static {
        fragmentCacheHashMap = new ConcurrentHashMap<>();
    }

    private static class ViewHolder {
        private static FlutterFragmentManager INSTANCE = new FlutterFragmentManager();
    }

    public static FlutterFragmentManager getInstance() {
        return ViewHolder.INSTANCE;
    }

    public void register(String key,FlutterFragment mFragment) {
        if (TextUtils.isEmpty(key) || mFragment == null) {
            LogUtil.d(TAG,"key或者目标fragment不能为空");
            return;
        }

        WeakReference<FlutterFragment> fragmentWeakRef = new WeakReference<>(mFragment);

        fragmentCacheHashMap.put(key, fragmentWeakRef);
    }

    public void unRegister(String key) {
        if (TextUtils.isEmpty(key)) {
            LogUtil.d(TAG,"key 不能为空");
            return;
        }

        fragmentCacheHashMap.remove(key);
    }

    public WeakReference<FlutterFragment> getregisteredFlutterFragment(String key) {
        if (TextUtils.isEmpty(key)) {
            LogUtil.d(TAG,"key 不能为空");
            return null;
        }

        return fragmentCacheHashMap.get(key);
    }

    public void unRegisterAll() {
        fragmentCacheHashMap.clear();
    }

    public void destoryAllFlutterFragment() {
        for(WeakReference<FlutterFragment> item : fragmentCacheHashMap.values()) {
            FlutterFragment mFragment = item.get();
            if (mFragment != null) {
                mFragment.onDestroyView();
            }
        }
    }
}
